package com.sky.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisKeyConstant;
import com.sky.dto.AdminRoleCreateDTO;
import com.sky.dto.AdminRoleDeleteDTO;
import com.sky.dto.AdminRolePageQueryDTO;
import com.sky.dto.AdminRoleUpdateDTO;
import com.sky.entity.AdminPermissions;
import com.sky.entity.AdminRoles;
import com.sky.result.Result;
import com.sky.service.AdminRoleService;
import com.sky.vo.AdminRoleVO;
import cn.mybatis.mp.core.mybatis.mapper.context.Pager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 管理员角色管理控制器
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "管理员角色相关接口")
@Slf4j
public class AdminRoleController {

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取所有角色列表
     * @return 角色列表
     */
    @GetMapping("/roles")
    @ApiOperation("获取所有角色列表")
    public Result<List<AdminRoles>> getAllRoles() {
        log.info("获取所有角色列表");
        List<AdminRoles> roles = adminRoleService.getAllRoles();
        return Result.success(roles);
    }

    /**
     * 分页查询角色列表
     * @param dto 分页查询参数
     * @return 分页结果
     */
    @PostMapping("/roles/page")
    @ApiOperation("分页查询角色列表")
    public Result<Pager<AdminRoleVO>> pageQuery(@RequestBody AdminRolePageQueryDTO dto) {
        log.info("分页查询角色列表：{}", dto);
        Pager<AdminRoleVO> pager = adminRoleService.pageQuery(dto, dto.getName());
        return Result.success(pager);
    }

    /**
     * 获取所有权限列表
     * @return 权限列表
     */
    @GetMapping("/permissions")
    @ApiOperation("获取所有权限列表")
    public Result<List<AdminPermissions>> getAllPermissions() {
        log.info("获取所有权限列表");
        List<AdminPermissions> permissions = adminRoleService.getAllPermissions();
        return Result.success(permissions);
    }

    /**
     * 新增角色
     * @param dto 角色信息
     * @return 操作结果
     */
    @PostMapping("/saveRoles")
    @ApiOperation("新增角色")
    public Result<Void> createRole(@RequestBody @Validated AdminRoleCreateDTO dto) {
        log.info("新增角色：{}", dto);
        AdminRoles role = new AdminRoles();
        role.setRoleName(dto.getName());
        role.setDescription(dto.getDescription());
        adminRoleService.createRole(role, dto.getPermissions());
        return Result.success();
    }

    /**
     * 更新角色
     * @param id 角色ID
     * @param dto 角色信息
     * @return 操作结果
     */
    @PutMapping("/roles/{id}")
    @ApiOperation("更新角色")
    public Result<Void> updateRole(@PathVariable("id") Integer id, @RequestBody @Validated AdminRoleUpdateDTO dto) {
        log.info("更新角色，id：{}，参数：{}", id, dto);
        // 确保路径参数和请求体中的ID一致
        if (!id.equals(dto.getId())) {
            throw new IllegalArgumentException("路径参数ID与请求体ID不一致");
        }
        
        AdminRoles role = new AdminRoles();
        role.setRoleId(dto.getId());
        role.setRoleName(dto.getName());
        role.setDescription(dto.getDescription());
        adminRoleService.updateRole(role, dto.getPermissions());
        return Result.success();
    }

    /**
     * 删除角色
     * @param dto 删除角色的参数（包含角色ID和验证码）
     * @return 操作结果
     */
    @DeleteMapping("/roles/{id}")
    @ApiOperation("删除角色")
    @SaCheckPermission(value = "roleManagement", orRole = {"SuperAdmin"})
    public Result<Void> deleteRole(@PathVariable("id") Integer id, @RequestBody @Validated AdminRoleDeleteDTO dto) {
        log.info("删除角色，id：{}，参数：{}", id, dto);
        
        // 确保路径参数和请求体中的ID一致
        if (!id.equals(dto.getRoleId())) {
            throw new IllegalArgumentException("路径参数ID与请求体ID不一致");
        }

        // 获取当前管理员ID
        Integer adminId = StpUtil.getLoginIdAsInt();

        // 验证验证码
        String redisKey = RedisKeyConstant.ADMIN_DELETE_ROLE_CODE + adminId + ":" + id;
        String code = (String) redisTemplate.opsForValue().get(redisKey);
        if (code == null || !code.equals(dto.getCode())) {
            throw new IllegalArgumentException(MessageConstant.VERIFICATION_CODE_ERROR);
        }

        // 删除角色
        adminRoleService.deleteRole(id);

        // 删除验证码
        redisTemplate.delete(redisKey);

        return Result.success();
    }
} 